import { load } from "cheerio"
import { randomInt } from "crypto"
import * as fs from "fs"

async function getWordAudioURL(word) {
    const r = await fetch(
        `https://dictionary.cambridge.org/zhs/%E8%AF%8D%E5%85%B8/%E8%8B%B1%E8%AF%AD-%E6%B1%89%E8%AF%AD-%E7%AE%80%E4%BD%93/${word}`
    )
    const html = await r.text()
    const $ = load(html)
    const posHeaderList = $(`.pos-header`)

    for (const posHeader of posHeaderList) {
        const wordStr = $(`.hw.dhw`, posHeader).text()
        if (word.toLowerCase() == wordStr) {
            const ukSource = $(`.uk source[type="audio/mpeg"]`, posHeader)
            const ukSrc = ukSource.attr("src")
            const usSource = $(`.us source[type="audio/mpeg"]`, posHeader)
            const usSrc = usSource.attr("src")
            if (ukSrc.startsWith("/") && usSrc.startsWith("/")) {
                return {
                    uk: `https://dictionary.cambridge.org${ukSrc}`,
                    us: `https://dictionary.cambridge.org${usSrc}`,
                }
            } else {
                throw `src is not / start`
            }
        }
    }
    throw `word is not pattern`
}

async function getAll() {
    const dictText = (await fs.promises.readFile(`./src/dict.json`)).toString()
    const dict = JSON.parse(dictText)
    const words = []
    for (let i = 0; i < dict.length; i++) {
        const w = dict[i]
        try {
            const url = await getWordAudioURL(w.word)
            w.pronounce.uk.audioFilePath = url.uk
            w.pronounce.us.audioFilePath = url.us
            words.push(w)
            console.log(`[${w.word}] get it. for ${i + 1}/${dict.length}`)
        } catch (e) {
            console.log(`[${w.word}] : -----------------------------------`)
            console.error(e)
        }
        await new Promise((r) => setTimeout(r, randomInt(100, 500)))
    }

    await fs.promises.writeFile(`./src/dict.json`, JSON.stringify(words))

    console.log(`.................................`)
    console.log(`全部执行完成，成功${words.length}个`)
}

getAll()
